package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.common.to.SkuHasStockTO;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTO;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Resource
    public ProductAttrValueService productAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Resource
    private AttrService attrService;
    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService  wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveSupInfo(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSupInfo(spuInfoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        Long spuInfoId = spuInfoEntity.getId();
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoId);
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.save(spuInfoDescEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoId,images);
        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> attrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = attrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValue.setAttrId(attr.getAttrId());
            productAttrValue.setSpuId(spuInfoId);
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setAttrName(attrEntity.getAttrName());
            productAttrValue.setQuickShow(attrEntity.getShowDesc());
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds,spuBoundTO);
        spuBoundTO.setSupId(spuInfoId);
        //远程调用coupon服务
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if(r.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }


        //5、保存当前spu对应的所有sku信息；
        List<Skus> skus = spuSaveVo.getSkus();
        skus.forEach(sku->{

            //5.1）、sku的基本信息；pms_sku_info
            String defaultImg="";

            for (Images image : sku.getImages()) {
                if(image.getDefaultImg()==1){
                    defaultImg=image.getImgUrl();
                }
            }

            SkuInfoEntity skuInfo = new SkuInfoEntity();
            //private String skuName;
            //private BigDecimal price;
            //private String skuTitle;
            //private String skuSubtitle;
            BeanUtils.copyProperties(sku,skuInfo);
            skuInfo.setSpuId(spuInfoEntity.getId());
            skuInfo.setSaleCount(0L);
            skuInfo.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfo.setBrandId(spuInfoEntity.getBrandId());
            skuInfo.setSkuDefaultImg(defaultImg);

            skuInfoService.saveSkuInfo(skuInfo);

            //5.2）、sku的图片信息；pms_sku_image
            Long skuId = skuInfo.getSkuId();
            List<SkuImagesEntity> collect1 = sku.getImages().stream().map(image -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(image.getImgUrl());
                skuImagesEntity.setDefaultImg(image.getDefaultImg());
                return skuImagesEntity;
            }).filter(entity->{
                return  !StringUtils.isEmpty(entity.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(collect1);

            // 没有图片路径的无需保存 (使用filter写完了)

            //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
            List<SkuSaleAttrValueEntity> collect2 = sku.getAttr().stream().map(a -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());

            skuSaleAttrValueService.saveBatch(collect2);

            //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sku,skuReductionTo);
            skuReductionTo.setSkuId(skuId);
            if(skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(new BigDecimal(BigInteger.ZERO))==1){
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if(r1.getCode()!=0){
                    log.error("远程保存sp优惠信息失败");
                }
            }
        });

    }

    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();

        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(e->{
                e.eq("id",key).or().like("spu_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId)&&!catelogId.equals("0")){
            wrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId)&&!brandId.equals("0")){
            wrapper.eq("brand_id",brandId);

        }

        String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(status)){
            wrapper.eq("publish_status",status);

        }

        //key: '华为',//检索关键字
        // catelogId: 6,//三级分类id
        // brandId: 1,//品牌id
        // status: 0,//商品状态

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper
        );



        return new PageUtils(page);
    }

    private void saveBaseSupInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void up(Long spuId) {
        List<SkuInfoEntity> skus= skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(sku -> {
            return sku.getSkuId();
        }).collect(Collectors.toList());
        //TODO 4.查询当前sku可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<AttrEntity> searchAttrIds= attrService.selectSearchAttrIds(attrIds);
        Set<Long> attrIdSet = searchAttrIds.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toSet());

        List<SkuEsModel.Attrs> collect = baseAttrs.stream().filter(item -> {
            return attrIdSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //TODO 1.发送远程调用，库存系统查询是否存库
        Map<Long, Boolean> map=null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIds);

            TypeReference<List<SkuHasStockTO>> typeReference = new TypeReference<List<SkuHasStockTO>>() {};
            map = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockTO::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务出现问题：原因",e);
        }
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> skuEsModelList = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            //skuPirce,skuImg
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            // hasStock,hotScore
            if(finalMap ==null){
                skuEsModel.setHasStock(true);
            }else{
                skuEsModel.setHasStock(finalMap.get(sku.getSkuId()));
            }

            //TODO 2.热度评分，0
            skuEsModel.setHotScore(0L);
            //TODO 3.查询品牌和分类里的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(collect);
            // brandName,brandImg,catelogName,attrs
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5.将数据发送给es进行保存：gukimall-search
        R r = searchFeignService.productStatusUp(skuEsModelList);
        if(r.getCode()==0){
            //TODO 6.成功后修改spu状态
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setUpdateTime(new Date());
            spuInfoEntity.setPublishStatus(ProductConstant.StatusEnum.SPU_UP.getCode());
            this.updateById(spuInfoEntity);
        }else{
            //TODO 7.重试调用？？接口幂等性？？.....以后整
        }



    }

    @Override
    public SpuInfoEntity getSpuBySkuId(Long skuId) {
        SkuInfoEntity sku = skuInfoService.getById(skuId);
        Long spuId = sku.getSpuId();
        SpuInfoEntity spu = getById(spuId);
        return spu;
    }

}